/**
 * 
 * 正常结果范式
 * {
 *  code: '正确状态码',
 *  data: '业务数据',
 * }
 * 错误结果范式
 * {
 *  code: '错误码'',
 *  error: 'human readable错误信息',
 *  extra: '附加信息',
 * }
 */
var crypto = require('crypto');

function wrapResult(result) {
    if (result.hasError) {
        return {
            code: result.errorCode,
            error: result.errorMessage,
            extra: result.errorExtra,
        };
    }
    return {
        code: 200,
        data: result.simpleValue ? result.simpleValue : result
    };
}

module.exports = (req, resp, next) => {
    resp.toApiJson = resp.toApiText = (message) => {
        let respResult = wrapResult(message);
        resp.json(respResult);
    };

    resp.toApiJson = resp.toApiText = (message) => {
        let respResult = wrapResult(message);
        resp.json(respResult);
    };
    resp.toSecureApiJson = resp.toApiText = (message) => {
        let token = req.headers['authorization'];
        if(!token) {
            throw Error('no authroization for this api but invoke `toSecureApiJson` at last!');
        }
        let respResult = wrapResult(message);
        var str = JSON.stringify(respResult);
        var cipher = crypto.createCipher('aes192', token);
        var enc = cipher.update(str, 'utf8', 'hex');
        enc += cipher.final('hex');
        resp.text(enc);
    };
    next();
}